package com.lanchewuyou.user.driver.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.layouts.ImageButton;
import com.lanchewuyou.user.driver.layouts.RippleView;
import com.lanchewuyou.user.driver.lipeiui.PickCarActivity;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.squareup.okhttp.Request;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 拍照显示/从相册选取显示并上传证件界面,宽度为600进行裁剪，压缩率为90
 * (弃用)
 */

public class PersonPhoActivity extends AppCompatActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private TextView titleText;
    private RippleView waitPho, takePho;
    private Button perphoNextBtn;
    private ProgressDialog progressDialog;
    private ImageView mainImage;
    private ImageButton imageButton1, imageButton2, imageButton3, imageButton4;
    int REQUEST_CODE_TAG = 1;//拍照请求标签，随着imagebutton改变
    int REQUEST_CODE_ALBUM = 5;
    private Button shangchuanshenfenzheng1, shangchuanshenfenzheng2, shangchuanjiashizheng, shangchuanxingshizheng;
    String SAVE_TAG1 = "shenfenzheng1";
    String SAVE_TAG2 = "shenfenzheng2";
    String SAVE_TAG3 = "jiashizheng";
    String SAVE_TAG4 = "xingshizheng";
    //图片文件夹
    private String PHOTO_FOLDER = new File(Environment.getExternalStorageDirectory(), "").getPath() + "/lanchewuyou/";

    private String PHOTO_PERSON_FOLDER;

    private String orderId;
    private static String DRIVERID;

    public static PersonPhoActivity instance;
    private long time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_pho);
        initViews();
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        DRIVERID = sharedPreferences.getString("driverid", "");
        instance = this;
        time = System.currentTimeMillis();
        orderId = PickCarActivity.orderId;
        //每个个人个人资料照片以订单id为名建立一个文件夹
        PHOTO_PERSON_FOLDER = PHOTO_FOLDER + orderId + "person/";
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(PHOTO_FOLDER);
            if (!file.exists()) {
                file.mkdir();
            } else {
                return;
            }
            File file1 = new File(PHOTO_PERSON_FOLDER);
            if (!file1.exists()) {
                file1.mkdir();
            } else {
                return;
            }
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    private void initViews() {
        mToolbar = (Toolbar) findViewById(R.id.person_pho_toolbar);
        mToolbar.setTitle("车主信息");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        titleText = (TextView) findViewById(R.id.pho_title_text);
        titleText.setText("车主身份证正面");
        mainImage = (ImageView) findViewById(R.id.person_main_photo);
        waitPho = (RippleView) findViewById(R.id.person_from_album);
        waitPho.setOnClickListener(this);
        takePho = (RippleView) findViewById(R.id.person_take_photo);
        takePho.setOnClickListener(this);
        imageButton1 = (ImageButton) findViewById(R.id.person_imgbtn1);
        imageButton1.setOnClickListener(this);
        imageButton1.setTextView("身份证正面");
        imageButton1.setImageBtnColor(1);
        imageButton2 = (ImageButton) findViewById(R.id.person_imgbtn2);
        imageButton2.setOnClickListener(this);
        imageButton2.setTextView("身份证反面");
        imageButton3 = (ImageButton) findViewById(R.id.person_imgbtn3);
        imageButton3.setOnClickListener(this);
        imageButton3.setTextView("车主驾驶证");
        imageButton4 = (ImageButton) findViewById(R.id.person_imgbtn4);
        imageButton4.setOnClickListener(this);
        imageButton4.setTextView("车主行驶证");
        perphoNextBtn = (Button) findViewById(R.id.person_pho_next_btn);
        perphoNextBtn.setOnClickListener(this);
        shangchuanshenfenzheng1 = (Button) findViewById(R.id.shangchuan_shenfenzheng1);
        shangchuanshenfenzheng1.setOnClickListener(this);
        shangchuanshenfenzheng2 = (Button) findViewById(R.id.shangchuan_shenfenzheng2);
        shangchuanshenfenzheng2.setOnClickListener(this);
        shangchuanjiashizheng = (Button) findViewById(R.id.shangchuan_jiashizheng);
        shangchuanjiashizheng.setOnClickListener(this);
        shangchuanxingshizheng = (Button) findViewById(R.id.shangchuan_xingshizheng);
        shangchuanxingshizheng.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.person_from_album:
                getImageFromAlbum();
                break;
            case R.id.person_take_photo:
                getImageFromCamera();
                break;
            case R.id.person_imgbtn1:
                REQUEST_CODE_TAG = 1;
                REQUEST_CODE_ALBUM = 5;
                titleText.setText("车主身份证正面");
                imageButton1.setImageBtnColor(1);
                imageButton2.setImageBtnColor(2);
                imageButton3.setImageBtnColor(2);
                imageButton4.setImageBtnColor(2);
                Bitmap imgbit1 = getBitmapFromFile(PHOTO_PERSON_FOLDER + SAVE_TAG1 + ".jpg");
                if (imgbit1 == null) {
                    imageButton1.setImageView(R.mipmap.pho_sma);
                    mainImage.setImageResource(R.mipmap.pho);
                } else {
                    imageButton1.setImageView(imgbit1);
                    mainImage.setImageBitmap(imgbit1);
                }
                break;
            case R.id.person_imgbtn2:
                REQUEST_CODE_TAG = 2;
                REQUEST_CODE_ALBUM = 6;
                titleText.setText("车主身份证反面");
                imageButton1.setImageBtnColor(2);
                imageButton2.setImageBtnColor(1);
                imageButton3.setImageBtnColor(2);
                imageButton4.setImageBtnColor(2);
                Bitmap imgbit2 = getBitmapFromFile(PHOTO_PERSON_FOLDER + SAVE_TAG2 + ".jpg");
                if (imgbit2 == null) {
                    imageButton2.setImageView(R.mipmap.pho_sma);
                    mainImage.setImageResource(R.mipmap.pho);
                } else {
                    imageButton2.setImageView(imgbit2);
                    mainImage.setImageBitmap(imgbit2);
                }
                break;
            case R.id.person_imgbtn3:
                REQUEST_CODE_TAG = 3;
                REQUEST_CODE_ALBUM = 7;
                titleText.setText("车主驾驶证");
                imageButton1.setImageBtnColor(2);
                imageButton2.setImageBtnColor(2);
                imageButton3.setImageBtnColor(1);
                imageButton4.setImageBtnColor(2);
                Bitmap imgbit3 = getBitmapFromFile(PHOTO_PERSON_FOLDER + SAVE_TAG3 + ".jpg");
                if (imgbit3 == null) {
                    imageButton3.setImageView(R.mipmap.pho_sma);
                    mainImage.setImageResource(R.mipmap.pho);
                } else {
                    imageButton3.setImageView(imgbit3);
                    mainImage.setImageBitmap(imgbit3);
                }
                break;
            case R.id.person_imgbtn4:
                REQUEST_CODE_TAG = 4;
                REQUEST_CODE_ALBUM = 8;
                titleText.setText("车主行驶证");
                imageButton1.setImageBtnColor(2);
                imageButton2.setImageBtnColor(2);
                imageButton3.setImageBtnColor(2);
                imageButton4.setImageBtnColor(1);
                Bitmap imgbit4 = getBitmapFromFile(PHOTO_PERSON_FOLDER + SAVE_TAG4 + ".jpg");
                if (imgbit4 == null) {
                    imageButton4.setImageView(R.mipmap.pho_sma);
                    mainImage.setImageResource(R.mipmap.pho);
                } else {
                    imageButton4.setImageView(imgbit4);
                    mainImage.setImageBitmap(imgbit4);
                }

                break;
            case R.id.shangchuan_shenfenzheng1:
                progressDialog = ProgressDialog.show(PersonPhoActivity.this, "正在上传", "稍等");
                File f1 = new File(PHOTO_PERSON_FOLDER, time + orderId + DRIVERID + ".jpg");
                if (f1.exists()) {
                    try {
                        OkHttpClientManager.postAsyn("http://www.lanchewuyou.com/index.php?g=Api&m=InsureDrive&a=PutCommonImage&orderid=423&driverid=10027&type=1", new OkHttpClientManager.StringCallback() {
                            @Override
                            public void onFailure(Request request, IOException e) {
                                Log.d("jpg", "error");
                                progressDialog.dismiss();
                            }

                            @Override
                            public void onResponse(String response) {
                                Log.d("jpg", response);
                                progressDialog.dismiss();
                            }
                        }, f1, "imageinfo");
                    } catch (IOException e) {
                        e.printStackTrace();
                        progressDialog.dismiss();
                    }
                } else {
                    Log.d("jpg", "null");
                    progressDialog.dismiss();
                }
                break;
            case R.id.shangchuan_shenfenzheng2:

                break;
            case R.id.shangchuan_jiashizheng:

                break;
            case R.id.shangchuan_xingshizheng:

                break;
            case R.id.person_pho_next_btn:
                Intent intent = new Intent(PersonPhoActivity.this, CarPhotoActivity.class);
                intent.putExtra("from", "");
                startActivity(intent);
                //finish();
                break;
            default:
                break;
        }

    }

    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent getCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            getCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(PHOTO_FOLDER + "mainpic.jpg")));
            startActivityForResult(getCamera, REQUEST_CODE_TAG);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    protected void getImageFromAlbum() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent getAlbum = new Intent(Intent.ACTION_PICK);
            getAlbum.setType("image/*");
            startActivityForResult(getAlbum, REQUEST_CODE_ALBUM);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_TAG) {
                try {
                    Bitmap take = getBitmapFromFile(PHOTO_FOLDER + "mainpic.jpg");
                    if (take.getWidth() < take.getHeight()) {
                        take = rotateBitmap(take, 90);
                    } else {
                        take = rotateBitmap(take, 0);
                    }
                    take = resizeBitmap(take, 600);
                    mainImage.setImageBitmap(take);
                    switch (REQUEST_CODE_TAG) {
                        case 1:
                            saveBitmap(take, SAVE_TAG1);
                            imageButton1.setImageView(take);
                            break;
                        case 2:
                            saveBitmap(take, SAVE_TAG2);
                            imageButton2.setImageView(take);
                            break;
                        case 3:
                            saveBitmap(take, SAVE_TAG3);
                            imageButton3.setImageView(take);
                            break;
                        case 4:
                            saveBitmap(take, SAVE_TAG4);
                            imageButton4.setImageView(take);
                            break;
                        default:
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else if (requestCode == REQUEST_CODE_ALBUM) {
                Uri uri = data.getData();
                try {
                    Bitmap albumBit = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                    if (albumBit.getWidth() < albumBit.getHeight()) {
                        albumBit = rotateBitmap(albumBit, 90);
                    } else {
                        albumBit = rotateBitmap(albumBit, 0);
                    }
                    albumBit = resizeBitmap(albumBit, 600);
                    mainImage.setImageBitmap(albumBit);
                    switch (REQUEST_CODE_ALBUM) {
                        case 5:
                            saveBitmap(albumBit, time + orderId + DRIVERID);
                            imageButton1.setImageView(albumBit);
                            break;
                        case 6:
                            saveBitmap(albumBit, SAVE_TAG2);
                            imageButton2.setImageView(albumBit);
                            break;
                        case 7:
                            saveBitmap(albumBit, SAVE_TAG3);
                            imageButton3.setImageView(albumBit);
                            break;
                        case 8:
                            saveBitmap(albumBit, SAVE_TAG4);
                            imageButton4.setImageView(albumBit);
                            break;
                        default:
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * 保存图片到具体位置
     *
     * @param bitmap
     */
    public void saveBitmap(Bitmap bitmap, String saveName) {
        File f = new File(PHOTO_PERSON_FOLDER, saveName + ".jpg");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 固定宽度压缩图片
     *
     * @param bitmap
     * @param newWidth
     * @return
     */
    public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float temp = ((float) height) / ((float) width);
        int newHeight = (int) ((newWidth) * temp);
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.recycle();
        return resizedBitmap;
    }

    /**
     * 从存储路径获取bitmap
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBitmapFromFile(String filePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        return bitmap;
    }

    /**
     * 旋转图片，使图片保持正确的方向。
     *
     * @param bitmap  原始图片
     * @param degrees 原始图片的角度
     * @return Bitmap 旋转后的图片
     */
    public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
        if (degrees == 0 || null == bitmap) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
        Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        if (null != bitmap) {
            bitmap.recycle();
        }
        return bmp;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_custom_infor, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
